package com.liuwei.msmall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liuwei.msmall.common.dto.SkuInfoDTO;
import com.liuwei.msmall.common.dto.SkuInfoWithSaleAttrDTO;
import com.liuwei.msmall.common.dto.SkuStockTo;
import com.liuwei.msmall.common.utils.PageUtils;
import com.liuwei.msmall.common.utils.Query;
import com.liuwei.msmall.common.utils.R;
import com.liuwei.msmall.product.dao.SkuInfoDao;
import com.liuwei.msmall.product.entity.BrandEntity;
import com.liuwei.msmall.product.entity.SkuImagesEntity;
import com.liuwei.msmall.product.entity.SkuInfoEntity;
import com.liuwei.msmall.product.entity.SpuInfoDescEntity;
import com.liuwei.msmall.product.feign.SeckillFeginService;
import com.liuwei.msmall.product.feign.WareFeignService;
import com.liuwei.msmall.product.service.*;
import com.liuwei.msmall.product.vo.SeckillSkuInfoVo;
import com.liuwei.msmall.product.vo.SkuItemSaleAttrVo;
import com.liuwei.msmall.product.vo.SkuItemVo;
import com.liuwei.msmall.product.vo.SpuItemAttrGroupVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Autowired
    private ThreadPoolExecutor threadPool;

    //查询商品图片信息
    @Autowired
    SkuImagesService skuImagesService;
    //查询spu介绍信息
    @Autowired
    SpuInfoDescService spuInfoDescService;
    @Autowired
    AttrGroupService attrGroupService;
    //查询商品销售属性
    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    BrandService brandService;

    @Autowired
    WareFeignService wareFeignService;

    @Autowired
    SeckillFeginService seckillFeginService;



    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        String key = (String)params.get("key");
        LambdaQueryWrapper<SkuInfoEntity> queryWrapper = new LambdaQueryWrapper<>();
        if(!StringUtils.isBlank(key)){
            queryWrapper.eq(SkuInfoEntity::getSkuId,key).or().like(SkuInfoEntity::getSkuName,key);

        }
        Long catelogId = Long.parseLong(params.get("catelogId").toString());
        if (catelogId.longValue()!=0){
            queryWrapper.eq(SkuInfoEntity::getCatalogId,catelogId);
        }

        Long brandId = Long.parseLong(params.get("brandId").toString());
        if (brandId.longValue()!=0){
            queryWrapper.eq(SkuInfoEntity::getBrandId,brandId);
        }

        String min = (String) params.get("min");
        String max = (String) params.get("max");
        BigDecimal minPrice = new BigDecimal(min);
        BigDecimal maxPrice = new BigDecimal(max);
        if (minPrice.compareTo(new BigDecimal("0")) == 1){
            queryWrapper.gt(SkuInfoEntity::getPrice,minPrice);
        }

        if (maxPrice.compareTo(new BigDecimal("0")) == 1){
            queryWrapper.lt(SkuInfoEntity::getPrice,maxPrice);
        }


        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public SkuItemVo item(Long skuId) throws ExecutionException, InterruptedException {

        SkuItemVo skuItemVo = new SkuItemVo();

        //开启一个有返回值的异步任务
        CompletableFuture<SkuInfoEntity> skuInfoFuture = CompletableFuture.supplyAsync(() -> {
            //1.查出sku基本信息 pms_sku_info
            SkuInfoEntity skuInfo = this.getBaseMapper().selectById(skuId);
            skuItemVo.setInfo(skuInfo);
            return skuInfo;
        }, threadPool);

        //调用远程服务查看是否有库存
        CompletableFuture<Void> setStockFuture = CompletableFuture.runAsync(() -> {

            R r = wareFeignService.getHasStock(Arrays.asList(skuId));
            if (r.getCode() == 0) {

                List<SkuStockTo> data = r.getData("data", new TypeReference<List<SkuStockTo>>() {
                });
                skuItemVo.setStock(data.get(0).getStock());

            }

        }, threadPool);

        //拿到当前sku属于哪个分类
        //用于查询属性分组

        CompletableFuture<Void> saleAttrFuture = skuInfoFuture.thenAcceptAsync((res) -> {
            //2.查出商品销售组合属性
            //按照spuId查出所有销售属性
            if (res!=null){
                List<SkuItemSaleAttrVo> skuItemSaleAttrVos = skuSaleAttrValueService.getSkuSaleAttrsBySpuId(res.getSpuId());
                skuItemVo.setSaleAttrVos(skuItemSaleAttrVos);
            }

        }, threadPool);

        CompletableFuture<Void> spuDescFuture = skuInfoFuture.thenAcceptAsync((res) -> {
            //4.查出商品描述信息 pms_spu_info_desc
            if (res!=null){
                SpuInfoDescEntity spuDesc = spuInfoDescService.getById(res.getSpuId());
                skuItemVo.setSpuInfoDesc(spuDesc);
            }

        }, threadPool);

        CompletableFuture<Void> skuImagesFuture = CompletableFuture.runAsync(() -> {
            //3.查出sku图片 pms_sku_images
            List<SkuImagesEntity> skuImages = skuImagesService.getImagesBySkuId(skuId);
            skuItemVo.setSkuImages(skuImages);
        }, threadPool);

        CompletableFuture<Void> attrsGroupFuture = skuInfoFuture.thenAcceptAsync((res) -> {
            //5.查出商品规格参数信息
            if (res!=null){
                List<SpuItemAttrGroupVo> attrsGroupVos = attrGroupService.getAttrGroupWithAttrBySpuId(res.getSpuId(), res.getCatalogId());
                skuItemVo.setAttrsGroupVos(attrsGroupVos);
            }

        }, threadPool);

        CompletableFuture<Void> brandFuture = skuInfoFuture.thenAcceptAsync((res) -> {
            if (res!=null){
                //6.设置品牌名称
                BrandEntity brandEntity = brandService.getById(res.getBrandId());
                skuItemVo.setBrandName(brandEntity.getName());
            }

        }, threadPool);

        //todo 查询商品对应的秒杀信息
        CompletableFuture<Void> seckillSkuFuture = CompletableFuture.runAsync(() -> {
            R r = seckillFeginService.getSkuSeckillInfo(skuId);
            if (r.getCode() == 0) {
                SeckillSkuInfoVo seckillSkuInfoVo = r.getData("data", new TypeReference<SeckillSkuInfoVo>() {
                });
                skuItemVo.setSeckillSkuInfoVo(seckillSkuInfoVo);
            }
        }, threadPool);

        //todo 调用远程服务查询商品促销信息

        //多任务组合,系统只等待耗时最长的任务
        CompletableFuture.allOf(saleAttrFuture,brandFuture,attrsGroupFuture,spuDescFuture,skuImagesFuture,setStockFuture,seckillSkuFuture).get();
        return skuItemVo;
    }


    @Override
    public SkuInfoWithSaleAttrDTO getSkuInfoWithSaleAttr(Long skuId) {

        SkuInfoWithSaleAttrDTO withSaleAttrDTO = new SkuInfoWithSaleAttrDTO();
        List<String> saleValueBySkuId = skuSaleAttrValueService.getSkuSaleValueBySkuId(skuId);
        SkuInfoEntity byId = this.getById(skuId);
        SkuInfoDTO skuInfoDTO = new SkuInfoDTO();
        BeanUtils.copyProperties(byId,skuInfoDTO);
        withSaleAttrDTO.setSkuInfoDTO(skuInfoDTO);
        withSaleAttrDTO.setSkuSaleAttrValues(saleValueBySkuId);
        return withSaleAttrDTO;
    }

}